package com.getpebble.android.ui;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import com.getpebble.android.common.core.trace.Trace;
import com.getpebble.android.main.activity.MainActivity;

public class UpdateActivity extends Activity {
    private static final String TAG = UpdateActivity.class.getSimpleName();

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Intent intent = getIntent();
        if (intent == null) {
            Trace.debug(TAG, "intent is null");
            moveToMainActivity();
            return;
        }
        Uri data = intent.getData();
        if (data == null) {
            Trace.debug(TAG, "data is null");
            moveToMainActivity();
            return;
        }
        String action = intent.getAction();
        if (action == null) {
            Trace.debug(TAG, "action is null");
            moveToMainActivity();
        } else if (action.equals("android.intent.action.VIEW")) {
            String scheme = data.getScheme();
            if (scheme == null) {
                Trace.debug(TAG, "scheme is null");
                moveToMainActivity();
            } else if (scheme.equals("http") || scheme.equals("https")) {
                Trace.debug(TAG, "Forwarding http sideloading intent to MainActivity: " + data);
                moveToMainActivity(intent);
            } else if (scheme.equals("file")) {
                Trace.debug(TAG, "Forwarding file sideloading intent to MainActivity: " + data);
                moveToMainActivity(intent);
            } else {
                Trace.debug(TAG, "Unsupported scheme for backwards compatible sideloading: " + scheme + " (" + data + ")");
                moveToMainActivity();
            }
        } else {
            Trace.debug(TAG, "invalid action: " + action);
            moveToMainActivity();
        }
    }

    private void moveToMainActivity() {
        startActivity(new Intent(this, MainActivity.class));
        finish();
    }

    private void moveToMainActivity(Intent intent) {
        intent.setClass(this, MainActivity.class);
        startActivity(intent);
        finish();
    }
}
